package com.asas.spaceflight.view;

import com.asas.spaceflight.model.Player;
import com.asas.spaceflight.model.Player.State;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class PlayerRender {
	
	private Player				player;
	
	private Texture				spritesTexture;	
	private Sprite[]			idleTextures;
	private Sprite[]			throttleTextures;
	
	private Animation			idleAnimation;
	private Animation			throttleAnimation;
	
	private Sprite				texture;
	private Animation			animation;	
	private float				stateTime;

	public PlayerRender(Player player) {
		this.player = player;
		
		spritesTexture = new Texture(Gdx.files.internal("data\\astronaut.png"));
		
		TextureRegion[][] regions = TextureRegion.split(spritesTexture,
				spritesTexture.getWidth()/4, spritesTexture.getHeight()/4);
		
		idleTextures = new Sprite[1];
		idleTextures[0] = new Sprite(regions[0][1]);
		
		throttleTextures = new Sprite[1];
		throttleTextures[0] = new Sprite(regions[0][0]);
		
		idleAnimation = new Animation(1f, idleTextures);
		throttleAnimation = new Animation(1f, throttleTextures);
		
		animation = idleAnimation;		
		stateTime = 0f;
		
		player.setWidth(idleTextures[0].getRegionWidth());
		player.setHeight(idleTextures[0].getRegionHeight());
	}
	
	public void update() {
		stateTime += Gdx.graphics.getDeltaTime();
		
		if (player.getState().equals(State.THROTTLE)) {
			animation = throttleAnimation;
		}
		else {
			animation = idleAnimation;			
		}
	}
	
	public void render(SpriteBatch batch) {
		texture = (Sprite)animation.getKeyFrame(stateTime, true);
		
		texture.setPosition(
				player.getPosition().x - player.getWidth()/2,
				player.getPosition().y - player.getHeight()/2);
					
		texture.setRotation(player.getAngle() - 90);
		
		texture.draw(batch);
	}

}
